package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     *
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody Map<String, String> map, HttpSession session) {
        //1. 随机生成验证码
        //String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String code = "1234";
        log.info("开始发送短信验证码code:{}", code);
        //2. 调用阿里云发送验证码
        //获取手机号
        String phone = map.get("phone");
        //SMSUtils.sendMessage("ABC商城", "SMS_208640979", phone, code);
        //3. 将验证码存入session
        session.setAttribute(phone, code);
        //4.返回发送验证码成功
        return R.success("发送短信验证码成功");

    }

    /**
     * 登陆功能
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
        //1. 获取用户输入的手机号和验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2. 获取session中的验证码
        String codeInSession = (String) session.getAttribute(phone);
        //3. 比对验证码
        if (StringUtils.isEmpty(codeInSession) || !codeInSession.equals(code)) {
            //3.1 验证码不一致，提示错误信息
            return R.error("验证码错误");
        }
        // 4. 判断用户是否是新用户，根据手机号查询数据库
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        //4.1 如果是新用户，添加到数据（注册）
        if(user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        } else{
            //老用户
            Integer status = user.getStatus();
            if(status == 0) {
                //用户已禁用
                return R.error("用户已禁用");
            }
        }
        //5. 登陆成功，把session中的验证码移除
        session.removeAttribute(phone);

        //6.将用户的id存入session
        session.setAttribute("user", user.getId());
        return R.success("登陆成功");
    }
}